package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController("adminCommonController")
@Api(tags = "文件上传")
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    /**
     * 用于上传文件到阿里云oss
     * @param multipartFile
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String>upload(@RequestParam(name = "file") MultipartFile multipartFile){
        //拿到原始文件名后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String originalFilenamePostfix = originalFilename.substring(originalFilename.lastIndexOf('.'));

        //利用uuid生成新的文件名
        String newFileName=UUID.randomUUID()+originalFilenamePostfix;

        //将该文件上传到阿里oss
        try {
            String url=AliOssUtil.upload(multipartFile.getBytes(), newFileName);
           log.info("文件上传成功!");
           return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.error("文件上传失败!");
    }
}
